package Class01_SampleUseDemo;

/**
 * Lambda表达式初体验
 * 代码更简洁
 * 函数式编程：更关注函数/功能，而非对象
 * 函数是“第一等公民”
 * 可以赋值给变量
 * 可以作为（其它函数的）参数进行传递
 * 可以作为（其它函数的）返回值
 */
public class L01SampleUseDemo {
    public static void main(String[] args) {
        //1.子类实现接口
        Factory factory = new SubClass();
        User user = (User) factory.getObject();
        System.out.println(user);

        //2.匿名内部类
        Factory factory1 = new Factory() {
            @Override
            public Object getObject() {
                return new User("zhangsan",8);
            }
        };
        User user1 = (User)factory1.getObject();
        System.out.println(user1);

        //3.Lambda表达式
        Factory factory2 = ()->{return new User("lisi",10);};
        User user2 = (User) factory2.getObject();
        System.out.println(user2);

        //4.Lambda表达式在使用的时候，如果函数体里面只有简单的表达式语句的时候，可以省略打括号
        Factory factory3 = ()->new User("wangwu",19);
        User user3 = (User) factory3.getObject();
        System.out.println(user3);

        //5.Lambda表达式可以作为参数进行传递
        User userFromFactory = getUserFromFactory(() -> {
            return new User("zhaoliu", 11);
        }, "User");
        System.out.println(userFromFactory);

        //6.Lambda表达式可以作为返回值
        Factory factory4 = getFactory();
        System.out.println(factory4.getObject());


    }

    public static User getUserFromFactory(Factory factory, String beanName) {
        Object obj = factory.getObject();
        if (obj != null && obj.getClass().getSimpleName().equals(beanName)) {
            return (User)obj;
        }
        return null;
    }

    public static Factory getFactory() {
        return () -> {return new User("钱七", 18);};
    }

}
